﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class ClipInfo
{
    public string eventID;
    public string audioName;
    public Vector3 clickPosition;
    //public bool isEnableRaycast;
    public bool isResumeTimeline;
    public ReceiverBaseMono receiverMono;
}

// A behaviour that is attached to a playable
public class ReceiverPlayableBehaviour : PlayableBehaviour, IEasyLoading, IEasyEffect
{
    public PlayableDirector playableDirector;
    public EClipType clipType;
    public string timelineID;

    public bool isPauseTimeline;
    public bool isResumeTimeline;
    public string eventID;
    public string nextTimelineID;
    public string audioName;
    public string effectPath;
    public string effectParent;
    public Vector3 clickPosition;
    public ReceiverBaseMono receiverMono;
    public HeroSelectManager.EHeroType heroType;

    private BaseTrackHolder holder;
    private bool isFirstPlay;

    public void Initialize(PlayableDirector director, GameObject bindingObject)
    {
        if (!Application.isPlaying)
            return;

        playableDirector = director;
        timelineID = director.name.Replace("Timeline:", "");
        BaseTrackHolder[] holderArray = bindingObject == null ? null : bindingObject.GetComponents<BaseTrackHolder>();
        if (holderArray != null)
        {
            foreach (BaseTrackHolder baseTrackHolder in holderArray)
            {
                baseTrackHolder.Initialize(timelineID);
                if (baseTrackHolder.GetType() != typeof(AnimationHolder))
                {
                    holder = baseTrackHolder;
                }
            }
        }
        isFirstPlay = true;
    }

    //public override void OnPlayableCreate(Playable playable)
    //{
    //    Debug.LogError("OnPlayableCreate");
    //}

    //public override void OnPlayableDestroy(Playable playable)
    //{
    //    Debug.LogError("OnPlayableDestroy");
    //}


    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {
        if (!Application.isPlaying)
            return;
        //Debug.LogError("OnBehaviourPlay");
        if (!isFirstPlay)
            return;
        isFirstPlay = false;

        if (isPauseTimeline)
        {
            isPauseTimeline = false;
            FTimelineDispatch.PauseTimeline(timelineID);
            //Debug.LogError("ON_TIMELINE_PAUSE");
            EventBus.Instance.BroadCastEvent<string>(EventID.ON_TIMELINE_PAUSE, eventID);
        }

        switch (clipType)
        {
            case EClipType.Event_Speak:
                FTimelineDispatch.RequestSpeak(() =>
                {
                    FTimelineDispatch.ResumeTimeline(timelineID);
                });

                break;
            case EClipType.Event_NextTimeline:
                //FTimelineDispatch.ToNextTimeline(timelineID, nextTimelineID);
                this.StartLoadingAndEndEx(()=> {
                    //Debug.LogError("111111");
                    FTimelineDispatch.PlayTimeline(nextTimelineID);
                }, () =>
                {
                    //Debug.LogError("22222222");
                    FTimelineDispatch.DestroyTimeline(timelineID);
                });
                break;
            case EClipType.Event_SelectCJFX:

                this.StartLoadingAndEndEx(() =>
                {
                    if (!string.IsNullOrEmpty(nextTimelineID))
                    {
                        FTimelineDispatch.DestroyTimeline(timelineID);
                    }

                    HeroSelectManager.Instance.Initialize();
                    HeroSelectManager.Instance.RequstHeroSelect(heroType, () => {
                        this.StartLoadingAndEndEx(() =>
                        {
                            HeroSelectManager.Instance.Dispose();
                            if (isResumeTimeline)
                                FTimelineDispatch.ResumeTimeline(timelineID);
                            if (!string.IsNullOrEmpty(nextTimelineID))
                            {
                                FTimelineDispatch.PlayTimeline(nextTimelineID);
                            }
                        },()=> {
                            //if (!string.IsNullOrEmpty(nextTimelineID))
                            //{
                            //    FTimelineDispatch.DestroyTimeline(timelineID);
                            //}
                        });

                    });
                });

                break;
            case EClipType.Event_Click:

                if (holder != null)
                {
                    ClipInfo clipInfo = new ClipInfo();
                    clipInfo.eventID = eventID;
                    clipInfo.audioName = audioName;
                    clipInfo.clickPosition = clickPosition;
                    clipInfo.isResumeTimeline = isResumeTimeline;
                    clipInfo.receiverMono = receiverMono;
                    holder.OnBehaviourPlay(clipInfo);
                    EventBus.Instance.BroadCastEvent<string>(EventID.ON_TIMELINE_RAYCAST_ENABLE, eventID);
                }

                break;
            case EClipType.Event_Custom:

                if (receiverMono != null)
                {
                    ReceiverBaseMono receiverObj = GameObject.Instantiate(receiverMono);
                    receiverObj.transform.SetParent(playableDirector.transform);
                    receiverObj.Initialize(timelineID);
                }
                if (holder != null)
                {
                    ClipInfo clipInfo = new ClipInfo();
                    clipInfo.eventID = eventID;
                    clipInfo.clickPosition = clickPosition;
                    clipInfo.isResumeTimeline = isResumeTimeline;
                    clipInfo.receiverMono = receiverMono;
                    holder.OnBehaviourPlay(clipInfo);
                }
                break;
            case EClipType.Event_Effect:
                string[] arr = effectParent.Split(';');
                Transform parent = playableDirector.transform.Find(arr[0]);
                if (parent != null)
                {
                    if (arr.Length == 2)
                    {
                        this.PlayEffectEx(effectPath, parent.FindChildEx(arr[1]), 15);
                    }
                    else
                    {
                        this.PlayEffectEx(effectPath, parent, 15);
                    }
                }
                
                break;
            default:
                if (holder != null)
                {
                    ClipInfo clipInfo = new ClipInfo();
                    clipInfo.eventID = eventID;
                    clipInfo.clickPosition = clickPosition;
                    clipInfo.isResumeTimeline = isResumeTimeline;
                    clipInfo.receiverMono = receiverMono;
                    holder.OnBehaviourPlay(clipInfo);
                }
                break;
        }
    }

    public override void OnBehaviourPause(Playable playable, FrameData info)
    {
        if (!Application.isPlaying)
            return;
        //Debug.LogError("OnBehaviourPause");
        if (!FTimelineDispatch.IsPlaying(timelineID))
            return;
        switch (clipType)
        {
            case EClipType.Event_Speak:
                break;
            case EClipType.Event_Click:

                if (holder != null)
                {
                    holder.OnBehaviourPause();
                }
                EventBus.Instance.BroadCastEvent<string>(EventID.ON_TIMELINE_RAYCAST_CLOSE, eventID);
                break;
            default:
                if (holder != null)
                {
                    holder.OnBehaviourPause();
                }
                break;
        }
    }

    //public override void OnGraphStart(Playable playable)
    //{
    //    Debug.LogError("OnGraphStart");
    //}

    //public override void OnGraphStop(Playable playable)
    //{
    //    Debug.LogError("OnGraphStop");
    //}

    //public override void PrepareFrame(Playable playable, FrameData frameData)
    //{
    //If the Scene GameObject exists, move it continuously until the Playable pauses
    //if (m_MySceneObject != null)
    //Move the GameObject using the velocity you set in your Playable Track's inspector
    //m_MySceneObject.transform.Rotate(m_SceneObjectVelocity);

    //}
}
